package attr

import (
	"context"
	"gorm.io/gorm"
	"mall/services/product/rpc/internal/mapper"
	"mall/services/product/rpc/internal/svc"
	"mall/services/product/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type DelAttrLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDelAttrLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelAttrLogic {
	return &DelAttrLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DelAttrLogic) DelAttr(in *pb.DelAttrDTO) (*pb.EmptyObj, error) {
	// 1.delete db
	deleteErr := l.deleteDB(in)
	if deleteErr != nil {
		return nil, deleteErr
	}
	// 2.return obj
	return &pb.EmptyObj{}, nil
}

func (l *DelAttrLogic) deleteDB(in *pb.DelAttrDTO) error {
	attrIdArr := in.AttrIdArr
	attrMapper := mapper.NewAttrMapper(l.ctx)
	return l.svcCtx.DBEngin.Transaction(func(tx *gorm.DB) error {
		// 1.1 del attr
		attrErr := attrMapper.DeleteCtx(tx, attrIdArr)
		if attrErr != nil {
			return attrErr
		}
		// 1.2 del category
		categoryMapper := mapper.NewAttrCategoryMapper(l.ctx)
		deleteCategoryErr := categoryMapper.DeleteCtxByAttrId(tx, attrIdArr)
		if deleteCategoryErr != nil {
			return deleteCategoryErr
		}
		// 1.3 del attr value
		valueMapper := mapper.NewAttrValueMapper(l.ctx)
		deleteValueErr := valueMapper.DeleteCtxByAttrId(tx, attrIdArr)
		if deleteValueErr != nil {
			return deleteValueErr
		}
		return nil
	})
}
